package org.argus.common.core.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.ContainerSerializer;
import com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase;
import com.fasterxml.jackson.databind.type.SimpleType;

import java.io.IOException;
import java.util.List;

/**
 * Long序列化成数字，而不是字符串 的序列化器，主要解决前端日期组件字符串形式的long值显示不正常问题。
 * @Author 刘文/Cliff Liu
 * @Date 2024/10/26
 */
public class LongListSerializer
        extends AsArraySerializerBase<List<?>> {

    private static final LongJavaScriptSafeSerializer serializer = new LongJavaScriptSafeSerializer();

    protected LongListSerializer() {
        this(SimpleType.constructUnsafe(Long.class), false, null, null);
    }
    protected LongListSerializer(JavaType elemType, boolean staticTyping, TypeSerializer vts,
                                 JsonSerializer<Object> valueSerializer)
    {
        super(List.class, elemType, staticTyping, vts, valueSerializer);
    }

    @Override
    public AsArraySerializerBase<List<?>> withResolved(BeanProperty property, TypeSerializer vts, JsonSerializer<?> elementSerializer, Boolean unwrapSingle) {
        return new LongListSerializer();
    }

    @Override
    public void serializeContents(List<?> value, JsonGenerator g, SerializerProvider provider)
            throws IOException {
        for (Object elem : value) {
            serializer.serialize(elem, g, provider);
        }
    }

    @Override
    public boolean hasSingleElement(List<?> value) {
        return (value.size() == 1);
    }

    @Override
    protected ContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts) {
        return new LongListSerializer();
    }
}
